/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.business.dao;

import han.bifang.common.entity.SoaResource;
import han.bifang.common.exception.BifangErrorCode;
import han.bifang.common.exception.BifangException;
import han.bifang.common.persist.dao.DaoManager;
import han.bifang.common.persist.page.Page;
import han.bifang.common.persist.page.PagedQuery;
import han.bifang.common.persist.tx.Tx;
import han.bifang.common.persist.tx.TxManager;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author Kent
 */
public class ResourceDao {

	public static String createResource(SoaResource res) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaResource s where s.entityId = ? and s.type = ?";
			List o = DaoManager.getDao().find(hql,
					new Object[] { res.getEntityId(), res.getType() });
			if (o.size() > 0) {
				throw new BifangException(BifangErrorCode.RESOURCE_EXIST_ERROR,
						"the entity ['" + res.getEntityId() + "' type '"
								+ res.getType()
								+ "'] has been registerred as a resource");
			}
			DaoManager.getDao().save(res);
			DaoManager.getDao().flush();
			tx.commit();
			return res.getId();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(ResourceDao.class);
			logger.error("ResourceDao.createResource()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"createResource() error", e);
		} finally {
			tx.end();
		}

	}
	
	public static void modifyResource(SoaResource res) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			DaoManager.getDao().merge(res);
			DaoManager.getDao().flush();
			tx.commit();
			

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(ResourceDao.class);
			logger.error("ResourceDao.modifyResource()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"modifyResource() error", e);
		} finally {
			tx.end();
		}

	}

	public static SoaResource getResource(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			SoaResource u = (SoaResource) DaoManager.getDao().get(
					SoaResource.class, id);
			tx.commit();

			return u;
		} catch (Throwable e) {
			Log logger = LogFactory.getLog(ResourceDao.class);
			logger.error("ResourceDao.getResource()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"getResource() error", e);
		} finally {
			tx.end();
		}

	}

	public static void removeResource(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			SoaResource u = (SoaResource) DaoManager.getDao().get(
					SoaResource.class, id);
			DaoManager.getDao().delete(u);
			tx.commit();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(ResourceDao.class);
			logger.error("ResourceDao.removeResource()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"removeResource() error", e);
		} finally {
			tx.end();
		}

	}

	public static void removeResourceByEntity(String type, String id)
			throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaResource s where s.type = ? and s.entityId = ?";
			List o = DaoManager.getDao().find(hql, new Object[] { type, id });
			DaoManager.getDao().deleteAll(o);
			tx.commit();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(ResourceDao.class);
			logger.error("ResourceDao.removeResource()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"removeResource() error", e);
		} finally {
			tx.end();
		}

	}

	public static SoaResource getResourceByEntity(String id,String type)
			throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaResource s where s.type = ? and s.entityId = ?";
			List o = DaoManager.getDao().find(hql, new Object[] { type, id });
			SoaResource ret = null;
			if(o.size() > 0 ){
				ret = (SoaResource)o.get(0);
			}
			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(ResourceDao.class);
			logger.error("ResourceDao.removeResource()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"removeResource() error", e);
		} finally {
			tx.end();
		}

	}

	public static List getResourcesOfRoleByPage(String roleId, int page,
			int pageSize) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "select s from SoaResource s, SoaRoleResRel r where r.compId.roleId = '"
					+ roleId + "' and s.id = r.compId.resId";
			PagedQuery pq = new PagedQuery(hql, page, pageSize);
			Page p = pq.getPage();
			int total = p.getPaginator().getPageNumber();
			ArrayList ret = new ArrayList();
			ret.add(total);
			ret.add(p.getList());
			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(ResourceDao.class);
			logger.error("ResourceDao.getResourcesOfRoleByPage()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"getResourcesOfRoleByPage() error", e);
		} finally {
			tx.end();
		}
	}
	
	public static List getResourcesNotOfRoleByPage(String roleId, String resourceType,String property1,
			String property2, String property3, int page,
			int pageSize) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaResource sr where sr.id not in (select s.id from SoaResource s, SoaRoleResRel r where r.compId.roleId = '"
					+ roleId + "' and s.id = r.compId.resId)";
			hql += " and sr.type = '" + resourceType + "'";
			
			if(property1 != null){
				hql += " and sr.property1 like '%" + property1 + "%'";
			}
			if(property2 != null){
				hql += " and sr.property2 like '%" + property2 + "%'";
			}
			if(property3 != null){
				hql += " and sr.property3 like '%" + property3 + "%'";
			}
			PagedQuery pq = new PagedQuery(hql, page, pageSize);
			Page p = pq.getPage();
			int total = p.getPaginator().getPageNumber();
			ArrayList ret = new ArrayList();
			ret.add(total);
			ret.add(p.getList());
			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(ResourceDao.class);
			logger.error("ResourceDao.getResourcesOfRoleByPage()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"getResourcesOfRoleByPage() error", e);
		} finally {
			tx.end();
		}
	}

}
